// import * as dhx from 'public/3thComponents/diagram/codebase/diagramWithEditor.js';
import 'public/3thComponents/diagram/codebase/diagramWithEditor.css';
import { mapState } from "vuex";

const idName = 'nodeId';
export default {
  data() {
    return {
      // 需要覆盖的参数
      modelName: '',
      modelObject: null,
      isInstance: false,
      // 内部参数
      menuShow: true,
      classObject: null,
      hierObject: null,
      configDrawer: {
        show: false,
      },
      editor: null, //diagram的编辑器
      diagram: null, //diagram实例
      rootData: {},
      curData: {},
      curCopyData: {},
      drawerSource: false,
      drawerCalcMessage: false,
      loading: false,
      curIndex: -1,
      calcMsg: {
        flag: true,
        content: [],
      },
    }
  },
  beforeMount() {
    this.classObject = this.modelName ? this.$modelObject.create(this.modelName) : {}
    this.hierObject = new this.modelObject()
  },
  mounted() {
    this.init()
    // setTimeout(() => {
    //   this.getRouting({ id: 3 }, false)
    // }, 1000);
  },
  methods: {
    async calcAllExp() {
      this.closeAllDrawer('drawerCalcMessage')
      if (this.drawerCalcMessage) {
        this.drawerCalcMessage = false
        return
      }
      this.loading = true
      let rootItem = this.hierObject.find(idName, this.rootData.nodeId)
      let { flag, res, errContent } = await this.hierObject.calcAllExp(rootItem)

      flag = !errContent.length
      this.calcMsg = {
        flag,
        content: !flag ? errContent : [this.lang.calcSuccess],
      }
      this.loading = false
      this.drawerCalcMessage = true
    },
    saveSource() {
      this.hierObject.loadSourceData()
      this.drawerSource = false
    },
    showHier() {
      console.log('this.hierObject', this.hierObject.web)
    },
    showSource() {
      this.closeAllDrawer('drawerSource')
      this.drawerSource = !this.drawerSource
    },
    closeAllDrawer(curDrawer = '') {
      curDrawer !== 'drawerCalcMessage' && (this.drawerCalcMessage = false)
      curDrawer !== 'drawerSource' && (this.drawerSource = false)
      curDrawer !== 'menuShow' && (this.menuShow = false)
    },
    addTpl(index) {
      return {
        name: `source${index}`,
      }
    },
    //#region 初始化图形
    init() {
      if (this.isInstance) {
        this.diagram = new dhx.Diagram(this.$refs.simpleMap, {
          type: 'default',
          width: "100%"
        })
        this._init_template();
        this._init_param();
        return 
      }
      this.editor = new dhx.DiagramEditor(this.$refs.simpleMap, this._getOptions());
      /**编辑器的diagram实例*/
      this.diagram=this.editor.diagram;
      /**初始化界面，去除工具栏、左右面板*/
      this._init_editorPanel();
      /**添加附加图元模板*/
      this._init_template();
      /**绑定diagram事件*/
      this._init_diagram_event();
      /**绑定editor事件*/
      this._init_editor_event();
      /**初始化参数*/
      this._init_param();
    },
    _getOptions() {
      return {
        shapeBarWidth: 320,
        scalePreview: 0.8,
        type: 'default', //"default" | "org" | "mindmap"模式中的一种（缺省|组织结构|脑图）
        select: false, //鼠标框选是否有效
        lineConfig: {
          //连接线配置
          lineType: 'line', //"dash" | "line"，虚线|实线
        },
        gridStep: 10, //网格间距
        /**以下default模式有效*/
        autoplacement: {
          //图元连接方式配置
          mode: 'edges', //"direct" | "edges"，edges为在图元边连接点处连接
          graphPadding: 100, //图元间距，缺省为200
        },
        lineGap: 50, //连接线与图元的间距
        /**以上default模式有效*/
        /***********以下配置编辑器*******************************************/
        /**配置 toolbar 的命令按钮是否可以显示*/
        controls: {
          apply: false,
          reset: false,
          export: false,
          import: false,
          autoLayout: false,
          historyManager: false,
          editManager: false,
          scale: true,
          gridStep: false,
        },
        editMode: true, //配置是否显示左右面板（左为图例，右为属性）
        shapeToolbar: [
          //配置选中图元时，图元顶部的工具栏
          {
            id: 'copy',
            content: '<i class="ivu-icon ivu-icon-md-copy" style="font-size: 20px"></i>',
            check: (shape) => {
              return ['routingRoot', 'workCenter'].includes(shape.type)
            },
          },
          {
            id: 'remove',
            content: '<i class="ivu-icon ivu-icon-md-trash" style="font-size: 20px"></i>',
            check: (shape) => {
              return !['routingRoot'].includes(shape.type)
            },
          },
        ],
        shapeSections: {},
      }
    },
    _getAdditionalTemplate() {
      let template = (shape) => {
        // let obj = this.hierObject.find(idName, shape.id) || shape
        let obj = shape.properties
        // console.log("file: diagramMixin.js:165 ", this.hierObject, shape.id, this.hierObject.find(idName, shape.id))

        return `
            <div class="shape-item flex-cm">
              <span class="icon"></span>
              <p>${obj.name === 'root' ? '根节点' : (obj.varName || ' ')}</p>
              <p>${obj.value || ''}</p>
            </div>
          `
      }
      let defaults = {
        shapeType: 'workCenter',
        title: 'workCenter',
        width: 90,
        height: 90,
      }
      return {
        routingRoot: {
          //block的基本配置defaults和样式template
          defaults,
          template,
        },
        workCenter: {
          //block的基本配置defaults和样式template
          defaults,
          template,
        },
      }
    },
    _init_param() {
      /**初始化数据*/
      this.diagram.data.parse([])
    },
    /**初始化工具栏、左右面板*/
    _init_editorPanel() {
      this.$nextTick(() => {
        const toolbar = document.querySelector('.dhx_topbar')
        const rightPanel = document.querySelector('.dhx_diagram_editor__sidebar')
        const leftPanel = document.querySelector('.dhx_diagram_editor_shapebar__container')
        toolbar.style.display = 'none'
        rightPanel.style.display = 'none'
        leftPanel.style.display = 'none'
      })
    },
    /**附加图元模板*/
    _init_template() {
      let additionalTemplate = this._getAdditionalTemplate()
      Object.keys(additionalTemplate).map((key) => {
        this.diagram.addShape(key, {
          template: additionalTemplate[key].template,
          defaults: additionalTemplate[key].defaults,
        })
      })
    },
    /**绑定editor事件*/
    _init_editor_event() {
      /**设置图元顶部工具栏的事件方法*/
      this.editor.events.on('beforeShapeIconClick', async (iconId, shape) => {
        switch (iconId) {
          case 'info':
            this.showProp(shape.id)
            break
          case 'remove':
            //  return await dispatch('removeModel',shape);
            return false
            break
          case 'add':
          case 'copy':
            this.curCopyData = shape
            break
        }
      })
    },
    /**绑定diagram事件*/
    _init_diagram_event() {
      let _this = this
      _this.diagram.events.on('itemDblClick', (id, event) => {
        this.showProp(id)
      })
      _this.diagram.events.on('change', (id, status, shape) => {
        if (!status || !shape || !shape.type) {
          return
        }
        switch (shape.type) {
          case 'line':
            if (!!shape.from && !!shape.to) {
              if (status === 'update') {
                _this._addLine(shape)
              }
              if (status === 'remove') {
                _this._removeLine(shape)
              }
            }
            break
          case 'workCenter':
          case 'routingRoot':
            if (status === 'add') {
              if (shape.type === 'routingRoot') {
                shape.shapeType = 'workCenter'
                shape.type = 'workCenter'
              }
              _this._addWC(shape)
            }
            if (status === 'remove') {
              _this._removeWC(shape)
            }
            break
          default:
            break
        }
      })
    },
    //#endregion 初始化图形

    // 查询根节点和全部子节点
    getRouting(row, init = true) {
      this.closeAllDrawer()
      let filter = row.name ? `name='${row.name}'` : `id=${row.id}`
      this.classObject.query(filter).then((flag) => {
        if (flag) {
          console.log("file: diagramMixin.js:276  this.classObject.query  this.hierObject:",this.classObject, this.hierObject,this.hierObject.web.data)
          this.hierObject.set(this.classObject.record.hier, this.classObject.record.web)
          this.rootData = { ...this.classObject.record, [idName]: this.hierObject.rootId }
          this.diagram.data.parse(this.hierObject.web.data)
        }
      })
    },
    saveRouting() {
      this.classObject.record = {
        ...this.classObject.record,
        hier: this.hierObject.hierProperties,
        web: {
          source: this.hierObject.web.source,
          data: this.diagram.data.serialize(),
        },
      }
      this.classObject.updateById().then((flag) => {
        if (flag) {
          this.diagram.paint()
        }
      })
    },
    showProp(id) {
      // let hierItem = this.hierObject.find(idName, id) || {}
      let shape = this.diagram.data.getItem(id) || {};
      let hierItem = shape.properties || {}

      this.curIndex = this.hierObject.findIndex(idName, id);
      this.curData = {...hierItem, nodeId: id}
      this.configDrawer.show = true
    },
    panelConfirm(properties) {
      console.log("file: diagramMixin.js:313  panelConfirm", properties)
      // this._updateProp(data)
      // this.diagram.paint()
      // this.configDrawer.show = false

      this._updateProp(properties)
      let hierItem = this.hierObject.hierProperties.content[this.curIndex]
      let shape=this.diagram.data.getItem(hierItem[idName]);

      if (shape && shape.properties) {
        shape.properties = properties
      }
      this.diagram.paint();
      this.configDrawer.show=false;
      this.hierObject.web.data = this.diagram.data.serialize()
    },
    panelCancel() {
      this.configDrawer.show = false
    },
    // hier 操作
    _updateProp(data) {
      let hierItem = this.hierObject.find(idName, data.nodeId)
      if (!hierItem) {
        return
      }
      let newItem = { ...hierItem, ...data }
      let shape = this.diagram.data.getItem(data.nodeId)

      this.updateChild(newItem)
      if (shape && shape.properties) {
        shape.properties = data
      }
    },
    _addWC(shape) {
      let fromId = this.curCopyData.id
      let newItem = this.addChild(shape, fromId)
      fromId && (this.diagram.data.add(
        { type: "line", from: fromId, to: newItem[idName],
          "fromSide": "right",  "toSide": "left", "added": true,
          connectType: "elbow", forwardArrow: "filled"
        }
      ))
      shape.properties = newItem
    },
    _removeWC(shape) {
      this.hierObject.delete(idName, {[idName]: shape.id})
      this.hierObject.hierProperties.content.forEach((item) => {
        if (item.nodeType !== 'root' && item.prev.includes(shape.id)) {
          item.prev = item.prev.filter((k) => k !== shape.id)
          // let shapeItem = this.diagram.data.getItem(item[idName])
          // shapeItem.properties = item
        }
      })
    },
    _addLine(line) {
      if (!line.to || !line.from) {
        return
      }
      /**连接线终点为root，则为非法*/
      if (line.to === this.rootData[idName]) {
        this.diagram.data.remove([line.id])
        return
      }
      line['forwardArrow'] = 'filled'
      line['added'] = true

      let prev = line.from
      let id = line.to
      let curItem = this.hierObject.find(idName, id)
      if (!curItem) {
        this.diagram.data.remove([line.id])
        return
      }
      let shape = this.diagram.data.getItem(id)

      if (!curItem.prev.includes(prev)) {
        curItem.prev.push(prev)
        this.updateChild(curItem)
        shape.properties = curItem
      } else {
        this.diagram.data.remove([line.id])
      }
    },
    _removeLine(line) {
      let prev = line.from
      let id = line.to
      let index = this.hierObject.findIndex(idName, id)
      if (index === -1) {
        return
      }
      let curItem = this.hierObject.hierProperties.content[index]
      let shape = this.diagram.data.getItem(id)

      curItem.prev = curItem.prev.filter((k) => k !== prev)
      this.updateChild(curItem, index)
      shape.properties = curItem
    },
    // 调用接口
    addChild(shape, fromId) {
      let newItem = {
        ...this.hierObject.itemTpl(),
        parentId: this.rootData[idName],
        [idName]: shape.id,
        prev: fromId ? [fromId] : [],
        nodeType: 'list',
      }
      this.hierObject.add(newItem)
      return newItem
    },
    updateChild(newItem) {
      this.hierObject.update(idName, newItem)
    },
  },
  computed: {
    ...mapState('admin/model', ['modelTree']),
    sourceColumns() {
      return [
        {
          key: 'name',
          title: 'name',
          width: 200,
          elementName: 'fieldCell',
          props: { config: { type: 'text', clearable: true } },
        },
        {
          key: 'model',
          title: 'model',
          elementName: 'fieldCell',
          props: { config: { type: 'cascader', options: this.modelTree } },
        },
        {
          key: 'operation',
          slot: 'operation',
        },
      ]
    },
    lang() {
      return {
        'zh-CN': {
          position: '当前记录',
          save: '保存',
          source: '配置数据源',
          loadData: '加载数据',
          calcResult: '计算结果',
          calcSuccess: '成功',
          calcFail: '失败',
        },
        'en-US': {
          position: 'current record',
          save: 'save',
          source: 'config data source',
          loadData: 'load data',
          calcResult: 'calc result',
          calcSuccess: 'success',
          calcFail: 'fail',
        },
      }[this.G_Locale]
    },
  },
}
